package com.sakiko.controller;

import com.sakiko.pojo.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    /*
        细节 1: 如果不符合规则，正常抛出异常，利用全局异常处理器进行处理
        细节 2: 接收参数校验结果 BingingResult 注意: BR必须紧跟接收对象
        细节 3: 非空类型校验
            a、@NotNull 非空，适合封装类型
            b、@NotBlank 非空，并且字符串不能是“” or "   "
            c、NotEmpty 非空，字符串不能是空串“”,检查集合和数组长度不为 0
     */
    // 用户信息保存
    @PostMapping
    public User saveUser(HttpServletRequest request, @Validated @RequestBody User user/*，HttpSession session*/, BindingResult result, HttpServletResponse response) { // @Validated [springmvc     @Valid [java
        if (result.hasErrors()) {
            // 获取所有字段错误
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError error : fieldErrors) {
                String field = error.getField(); // 获取出错的字段名
                String message = error.getDefaultMessage(); // 获取错误消息
                System.out.println("Field: " + field + ", Error: " + message);
            }
            return null;
        }

        System.out.println("UserController.saveUser");
        System.out.println("user = " + user);
        return user;
    }
}
